<?php

namespace app\user\controller;

use app\common\lib\Netease as ease;
use app\common\model\RelativeRelation;
use app\common\model\Tag as TagModel;
use app\common\model\Tag;
use app\common\model\TagRecord;
use app\common\model\UserRelation as RelationModel;
use think\facade\Log;
use think\Request;
use app\common\model\User as UserModel;
use app\common\controller\Base;
use app\common\lib\Util;
use app\common\model\Plan;
use app\common\lib\CheckDate;


class User extends Base
{
    protected $request;

    public function __construct(Request $request)
    {
        parent::__construct();
        $this->request = $request;
    }

    //搜索好友接口
    public function findByPhoneNum(UserModel $userModel)
    {
        $phoneNum = $this->request->param('phone_num');
        if (empty($phoneNum) && $phoneNum != '0') {
            return Util::apiResponse([], '搜索内容不能为空', 400);
        }
        $accid = $userModel->where(['phone_num' => $phoneNum, 'is_user' => 1])->value('accid');
        return Util::apiResponse(['accid' => $accid ? $accid : ''], '', 200);
    }

    //修改me_id
    public function updateMeId(ease $ease, UserModel $userModel)
    {
        $meId = $this->request->param('me_id');
        $userInfo = $ease->getUinfos($this->accid);
        if ($userInfo['error'] == 1) {
            return Util::apiResponse([], $userInfo['message'], 400);
        }
        $ex = json_decode($userInfo['ex'], true);
        if (!isset($ex['me_update_time']) || empty($ex['me_update_time'])) {
            $ex['me_id'] = $meId;
            $ex['me_update_time'] = time();
            $userModel->startTrans();
            $updateMeIdResult = $userModel->save(['me_id' => $meId], ['id' => $this->userId]);
            if ($updateMeIdResult === false) {
                $userModel->rollback();
                return Util::apiResponse([], '操作失败', 400);
            }
            $data = ['accid' => $this->accid, 'ex' => $ex];
            $updateInfoResult = $ease->updateUinfo($data);
            if (!$updateInfoResult) {
                $userModel->rollback();
                return Util::apiResponse([], '参数错误', 400);
            }
            if ($updateInfoResult['error'] == 1) {
                $userModel->rollback();
                return Util::apiResponse([], $updateInfoResult['message'], 400);
            }
            $userModel->commit();
            return Util::apiResponse([], '修改成功', 200);
        }
        return Util::apiResponse([], '你已经修改过一次了，不能再修改了', 400);
    }

    //搜索好友 方法
    public function getAccidByPhoneNum($phoneNum)
    {
        if (empty($phoneNum) && $phoneNum != '0') {
            return Util::apiResponse([], '搜索内容不能为空', 400);
        }
        $accid = UserModel::where(['phone_num' => $phoneNum, 'is_user' => 1])->value('accid');
        return $accid ? $accid : '';
    }

    //评价标签list
    public function tagList(TagModel $tagModel)
    {
        $tagList = $tagModel->field('id,tag_name,positive_score1,positive_score2,negative_score1,negative_score2')
            ->order('create_time desc')->select();
        return Util::apiResponse(['tag_list' => $tagList], '', 200);
    }

    //评价标签
    public function doTagComment(TagModel $tagModel, UserModel $user, TagRecord $tagRecordModel, ease $ease)
    {
        $faccid = $this->request->param('faccid');
        $fid = $user->where(['accid' => $faccid])->value('id');
        if (!$fid) {
            return Util::apiResponse([], '好友不存在', 400);
        }
        if ($this->accid == $faccid) {
            return Util::apiResponse([], '参数格式错误', 400);
        }
        //验证tagid_score参数json格式
        $tagidScore = json_decode($this->request->param('tagid_score'), true);
        if (!$tagidScore) {
            return Util::apiResponse([], '参数格式错误', 400);
        }
        $arrTagScore = [];
        foreach ($tagidScore as $k => $v) {
            if (!array_key_exists('id', $v)) {
                return Util::apiResponse([], '参数格式错误', 400);
            }
            if (!array_key_exists('score', $v)) {
                return Util::apiResponse([], '参数格式错误', 400);
            }
            $exist = $tagModel->where(['id' => $v['id'], 'positive_score1|positive_score2|negative_score1|negative_score2' => $v['score']])
                ->value('id');
            if (!$exist) {
                return Util::apiResponse([], '参数错误', 400);
            }
            $arrTagScore[$k]['id'] = $v['id'];
            $arrTagScore[$k]['score'] = $v['score'];
        }
        // 查询评价记录
        $record = $tagRecordModel->where(['user_id' => $fid, 'op_user_id' => $this->userId])
            ->whereTime('create_time', 'month')->find();
//        if($record){
//            return Util::apiResponse([], '每个月只能评价一次', 400);
//        }
        //插入评价记录
        $tagRecord = [
            'user_id' => $fid,
            'tagid_score' => json_encode($arrTagScore, JSON_UNESCAPED_UNICODE),
            'op_user_id' => $this->userId
        ];
        $tagResult = $tagRecordModel->save($tagRecord);
        if (!$tagResult) {
            return Util::apiResponse([], '评价失败', 400);
        }
        //获取并更新用户 ex 字符串
        $fidInfo = $ease->getUinfos([$faccid]);
        if ($fidInfo['error'] == 1) {
            $tagRecordModel::destroy(['id' => $tagRecordModel->insertGetId(), 'user_id' => $fid, 'op_user_id' => $this->userId]);
            return Util::apiResponse([], $fidInfo['message'], 400);
        }
        $ex = json_decode($fidInfo['ex'], true);
        //所有标签分数list
        $tagidScoreList = [];
        $idScores = [];
        $record = $tagRecordModel->where(['user_id' => $fid, 'op_user_id'=>$this->userId])->field('tagid_score')->select();
        $arr = [];
        if (($len = count($record)) > 0) {
            foreach ($record as $key => $value) {
                $value['tagid_score'] = json_decode($value['tagid_score'], true);
                foreach ($value['tagid_score'] as $k2 => $v2) {
                    $tagidScoreList[$key][$k2]['id'] = $v2['id'];
                    $tagidScoreList[$key][$k2]['score'] = $v2['score'];
                }
            }
            //获取平均分
            foreach ($tagidScoreList as $v3) {
                foreach ($v3 as $v4) {
                    $ids = array_column($idScores, 'id');
                    if (!in_array($v4['id'], $ids)) {
                        $idScores[$v4['id']]['id'] = $v4['id'];
                        $idScores[$v4['id']]['sum_score'] = $v4['score'];
                    } else {
                        $idScores[$v4['id']]['sum_score'] = $idScores[$v4['id']]['sum_score'] + $v4['score'];
                    }
                }
            }
            foreach ($idScores as $v5) {
                $tagName = $tagModel->where(['id' => $v5['id']])->value('tag_name');
                $average_score = $v5['sum_score'] / $len;
                //$str. = $tagName . ' ' . round($average_score, 2) . ',';
                $arr[] = ['id'=>$v5['id'],'tag_name'=>$tagName.' '.round($average_score, 2)];
            }
        }
        //去掉,
        //$str = substr($str, 0, -1);
        //$ex['tag'] = '学习 1,感恩 -1,恒心 2,节俭 1,勤奋 -2,运动 -1';
        $ex['tag'] = $arr;
        $data = ['accid' => $faccid, 'ex' => $ex];
        $result = $ease->updateUinfo($data);
        if ($result == false) {
            return Util::apiResponse([], '参数错误', 400);
        }
        if ($result['error'] == 1) {
            return Util::apiResponse([], $result['message'], 400);
        }
        $tagRecordModel->commit();
        return Util::apiResponse([], '评价成功', 200);
    }

    //关系下拉列表
    public function relationList(RelationModel $relationModel)
    {
        $relationList = $relationModel->field('id,name')->select();
        return Util::apiResponse(['relation_list' => $relationList], '', 200);
    }

    //设置好友关系
    public function setRelation(RelationModel $relationModel,RelativeRelation $relative,ease $ease)
    {
        $faccid = $this->request->param('faccid');
        $relationId = $this->request->relation_id;
        $relationList = $relationModel->field('id,name')->where(['id' => $relationId])->find();
        if (!$relationList) {
            return Util::apiResponse([], '参数错误', 400);
        }
        if ($this->accid == $faccid) {
            return Util::apiResponse([], '参数格式错误', 400);
        }
        //获取好友列表 并同时获取对应的ex内容
        $data = ['accid' => $this->accid, 'updatetime' => 1563847394];
        $result = $ease->friendList($data);
        if ($result == false) {
            return Util::apiResponse([], '参数错误', 400);
        }
        if ($result['error'] == 1) {
            return Util::apiResponse([], $result['message'], 400);
        }
        $ex = [];
        foreach ($result['list'] as $v) {
            if ($v['faccid'] == $faccid && isset($v['ex'])) {
                $ex = json_decode($v['ex'], true);
            }
        }
        $ex['relation'] = ['id' => $relationList['id'], 'name' => $relationList['name']];
        //亲属关系记录增加
        $existId = $relative->where(['accid'=>$this->accid,'faccid'=>$faccid])->value('id');
        $relative->startTrans();
        $relativeData = ['accid'=>$this->accid,'faccid'=>$faccid,'relation'=>json_encode($ex['relation'],JSON_UNESCAPED_UNICODE)];
        if($existId){
             $relative->save($relativeData,['id'=>$existId]);
        }else{
             $relative->save($relativeData);
        }
        $updateData = [
            'accid' => $this->accid,
            'faccid' => $faccid,
            'ex' => $ex
        ];
        $updateResult = $ease->updateFriendInfo($updateData);
        if ($updateResult['error'] == 1) {
            $relative->rollback();
            return Util::apiResponse([], $updateResult['message'], 400);
        }
        $relative->commit();
        return Util::apiResponse([], '设置好友关系成功', 200);
    }

    //查询某个好友设置的亲属关系
    public function getRelativeRelation(RelativeRelation $relative){
        $faccid = $this->request->param('faccid');
        $relation = $relative->where(['accid'=>$this->accid,'faccid'=>$faccid])->value('relation');
        if($relation){
            $relation = json_decode($relation,true);
        }else{
            $relation = [];
        }
        return Util::apiResponse($relation,'',200);
    }

    //计划
    public function createPlan(Plan $planModel)
    {
        $remindMsg = $this->request->param('remind_msg');
        if (empty($remindMsg) && $remindMsg != '0') {
            return Util::apiResponse([], '请输入提醒内容', 400);
        }
        $startTime = intval($this->request->param('start_time'));
        $endTime = intval($this->request->param('end_time'));
        if ($startTime == 0 || $endTime == 0) {
            return Util::apiResponse([], '请选择起止时间', 400);
        }
        if ($endTime < $startTime) {
            return Util::apiResponse([], '结束日期不能小于起始日期', 400);
        }
        //提前提醒时间 [5,30,60,120]
        $preTimes = intval($this->request->param('pre_times'));
        if (!in_array($preTimes, [0, 5, 30, 60, 120])) {
            return Util::apiResponse([], '参数错误', 400);
        }
        //循环提醒
        $circulation = $this->request->param('circulation');
        if ($circulation && !in_array($circulation, [0, 'day'])) {
            return Util::apiResponse([], '参数错误', 400);
        }
        $longitude = $this->request->param('longitude');
        $latitude = $this->request->param('latitude');
        $remark = $this->request->param('remark');
        $data = array(
            'user_id' => $this->userId,
            'type' => 1,
            'remind_msg' => $remindMsg,
            'start_time' => $startTime,
            'end_time' => $endTime,
            'pre_times' => $preTimes ? $preTimes : 0,
            'circulation' => $circulation ? $circulation : 0,
            'longitude' => $longitude ? $longitude : '',
            'latitude' => $latitude ? $latitude : '',
            'remark' => $remark ? $remark : ''
        );
        $result = $planModel->save($data);
        if ($result) {
            return Util::apiResponse([], '操作成功', 200);
        }
        return Util::apiResponse([], '操作失败', 400);
    }

    //目标
    public function createPurpose(Plan $planModel)
    {
        $remindMsg = $this->request->param('remind_msg');
        if (empty($remindMsg) && $remindMsg != '0') {
            return Util::apiResponse([], '请输入提醒内容', 400);
        }
        $targetTime = intval($this->request->param('target_time'));
        if ($targetTime == 0) {
            return Util::apiResponse([], '请选择时间', 400);
        }
        //提前提醒时间 [5,30,60,120,1440,2880]
        $preTimes = intval($this->request->param('pre_times'));
        if (!in_array($preTimes, [0, 5, 30, 60, 120, 1440, 2880])) {
            return Util::apiResponse([], '参数错误', 400);
        }
        //循环提醒
        $circulation = $this->request->param('circulation');
        if ($circulation && !in_array($circulation, [0, 'day', 'week', 'month', 'year'])) {
            return Util::apiResponse([], '参数错误', 400);
        }
        //验证时间
        $circulation_time = $this->request->param('circulation_time');
        CheckDate::check($circulation, $circulation_time);
        $longitude = $this->request->param('longitude');
        $latitude = $this->request->param('latitude');
        $remark = $this->request->param('remark');
        $data = array(
            'user_id' => $this->userId,
            'type' => 2,
            'remind_msg' => $remindMsg,
            'target_time' => $targetTime,
            'pre_times' => $preTimes ? $preTimes : 0,
            'circulation' => $circulation ? $circulation : 0,
            'circulation_time' => $circulation_time ? $circulation_time : 0,
            'longitude' => $longitude ? $longitude : '',
            'latitude' => $latitude ? $latitude : '',
            'remark' => $remark ? $remark : ''
        );
        $result = $planModel->save($data);
        if ($result) {
            return Util::apiResponse([], '操作成功', 200);
        }
        return Util::apiResponse([], '操作失败', 400);
    }

    //备忘录
    public function memo(Plan $planModel)
    {
        $list = $planModel->field('create_time,remind_msg')->where(['user_id' => $this->userId])
            ->order('create_time desc')->paginate(15)->toArray();
        if (count($list['data']) > 0) {
            foreach ($list['data'] as &$v) {
                $v['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
            }
        }
        return Util::apiResponse($list, '', 200);
    }
}
